#include"x264api.h"

uint32_t X264GetNextNaluSize(FILE*f264){
#define NALU_BUFFER_SIZE 4096
	uint32_t startpos=0;
	uint32_t readsize=0;
	uint32_t countsize=0;
	uint32_t headsize=0;
	uint8_t buff[NALU_BUFFER_SIZE];
	uint8_t checknextnalu=0;
	uint8_t bFirst=1;
	uint8_t bFindNextPos=0;
	if(f264==NULL||feof(f264))
		return 0;
	startpos=ftell(f264);
	readsize=fread(buff,1,NALU_BUFFER_SIZE,f264);
	if (readsize==0){
		return 0;
	}
	if((buff[0]==0x00)&&(buff[1]==0x00)&&(buff[2]==0x00)&&(buff[3]==0x01)){
		headsize=4;
	}else
	if((buff[0]==0x00)&&(buff[1]==0x00)&&(buff[2]==0x01)){
		headsize=3;
	}else{
		printf("can't find nalu head\n");
		return 0;
	}
	while(!bFindNextPos){
		uint32_t i=0;
		if(bFirst){
			i=headsize;
			bFirst=0;
		}else{
			readsize=fread(buff,1,NALU_BUFFER_SIZE,f264);
			if(readsize==0){
				bFindNextPos=1;
				break;
			}
		}
		for(;i<readsize;i++){
			countsize++;
			if(buff[i]==0x00){
				checknextnalu++;
			}else
			if(buff[i]==0x01){
				if(checknextnalu==2||checknextnalu==3){
					checknextnalu++;
					bFindNextPos=1;
					break;
				}else{
					checknextnalu=0;
				}
			}else{
				checknextnalu=0;
			}
		}
		if(bFindNextPos){
			countsize-=checknextnalu;
			break;
		}
	}
	fseek(f264,startpos+headsize,SEEK_SET);
	return countsize;
}
void X264GetNaluBuffer(FILE*f264,uint8_t*buffer,uint32_t nalusize){
	fread(buffer,1,nalusize,f264);
}